﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using EOSCRM.Domain;
using EOSCRM.Util;
using EOSCRM.Web.Common;
using EOSCRM.Dao;
using EOSCRM.Web.Shared;

namespace EOSCRM.Web.Forms.DongHo
{
    public partial class ThayDongHo : Authentication
    {
        private readonly KhachHangDao _khDao = new KhachHangDao();
        private readonly KhuVucDao _kvDao = new KhuVucDao();
        private readonly LoaiDongHoDao _loaiDhDao = new LoaiDongHoDao();
        private readonly ThayDongHoDao _thaydonghoDao = new ThayDongHoDao();
        private readonly PhuongDao phuongDao = new PhuongDao();
        private readonly NhanVienDao _nvDao = new NhanVienDao();
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                

                if (!Page.IsPostBack)
                {
                    LoadStaticReferences();
                    BindGrid();
                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        private void LoadStaticReferences()
        {
            try
            {
                CommonFunc.BindDropDownList(ddlLoaiKhachHang, new LoaiKhachHangDao().GetList(), "TENLOAI", "MALOAI", true);
                CommonFunc.BindDropDownList(ddlKHUVUC, _kvDao.GetList(), "TENKV", "MAKV", true);
                CommonFunc.BindDropDownList(ddlPHUONG, phuongDao.GetList(), "TENPHUONG", "MAPHUONG", true);
                CommonFunc.BindDropDownList(ddlLydoThay, new LyDoThayDongHoDao().GetList(), "TENLYDO", "MALYDO", false);
                CommonFunc.BindDropDownList(cboLoaiDh, _loaiDhDao.GetList(), "MALDH", "MALDH", false);

                txtNgayThay.Text=DateTime.Now.ToString("dd/MM/yyyy");
                txtNgayHoanThanh.Text = DateTime.Now.ToString("dd/MM/yyyy");
                txtNgayXuat.Text = DateTime.Now.ToString("dd/MM/yyyy");
                txtNgayLapBienBan.Text = DateTime.Now.ToString("dd/MM/yyyy");
                txtChiSoMoi.Text = "0";
                txtSoTien.Text = "0";
                linkdetail.Visible = false;
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }
        private Mode UpdateMode
        {
            get
            {
                try
                {
                    if (Session[SessionKey.MODE] != null)
                    {
                        var mode = Convert.ToInt32(Session[SessionKey.MODE]);
                        return (mode == Mode.Update.GetHashCode()) ? Mode.Update : Mode.Create;
                    }

                    return Mode.Create;
                }
                catch (Exception)
                {
                    return Mode.Create;
                }
            }

            set
            {
                Session[SessionKey.MODE] = value.GetHashCode();
            }
        }
        protected THAYDONGHO Obj {
            get
            {
                if (Isvaliddata()==false)
                {
                    return null;
                }
                var obj = new THAYDONGHO
                {
                    
                    IDKH = txtIDKH.Text,
                    
                    MALDH = cboLoaiDh.SelectedValue.ToString(),
                    MADH = txtMaDongho.Text.Trim(),
                    KICHCO = ddlKICHCODH.SelectedValue.ToString(),
                    GHICHU = txtGhiChu.Text,
                    SOTEM = txtSoTem.Text,
                    NOISANXUAT=txtNoiSanXuat.Text,
                    HANKIEMDINH=txtHanKiemDinh.Text,
                    CHISOCU=Decimal.Parse(txtChiSoCu.Text),
                    CHISOMOI=Decimal.Parse(txtChiSoMoi.Text),
                    DONVIKIEMDINH=txtDonViKiemDinh.Text,
                    CONGVIEC=ddlNoiDungCongViec.SelectedValue,
                    MALYDOTHAY=ddlLydoThay.SelectedValue,
                    PHIEUXUAT=txtSoPhieu.Text.Trim(),
                    NGAYXUAT=DateTimeUtil.GetVietNamDate(txtNgayXuat.Text.Trim()),
                    NGAYLBB=DateTimeUtil.GetVietNamDate(txtNgayLapBienBan.Text.Trim()),
                    TINHTRANG=checktinhtrang.Checked,
                    MANVLBB=txtNhanVienLapBienBan.Text.Trim(),
                    
                };
                if(checktinhtrang.Checked)
                {
                        obj.NGAYTD = DateTimeUtil.GetVietNamDate(txtNgayThay.Text.Trim());
                        obj.NGAYHT = DateTimeUtil.GetVietNamDate(txtNgayHoanThanh.Text.Trim());
                        obj.MANVTD = txtNhanVienTH.Text.Trim();
                }
                
                obj.SOLUONG = int.Parse(txtSoLuong.Text.Trim());
                obj.TIEN = decimal.Parse(txtSoTien.Text.Trim());
                obj.TIENNHANCONG = decimal.Parse(txtNhanCong.Text.Trim());
                obj.ISMUAMOI = checkMuaMoi.Checked;
                return obj;
            }
        }
        
        protected bool Isvaliddata()
        {
            // check chi so cu
            if (string.IsNullOrEmpty(txtChiSoCu.Text))
            {
                ShowError("Chỉ số cũ không được trống");
                return false;
            }
            if (CheckUtil.IsNaturalNumber(txtChiSoCu.Text) == false)
            {
                ShowError("Chỉ số cũ phải là số nguyên dương");
                return false;
            }
            // check chi so moi
            if (string.IsNullOrEmpty(txtChiSoMoi.Text))
            {
                ShowError("Chỉ số mới không được trống");
                return false;
            }
            //if (CheckUtil.IsNaturalNumber(txtChiSoMoi.Text) == false)
            //{
            //    ShowError("Chỉ số mới phải là số nguyên dương");
            //    return false;
            //}
            try
            {
                int chisocu = int.Parse(txtChiSoCu.Text);
                int chsmoi = int.Parse(txtChiSoMoi.Text);
                if (chsmoi > chisocu)
                {
                    ShowError("Chỉ số mới không được lớn hơn chỉ số cũ");
                    return false;
                }
            }
            catch
            {
                ShowError("Kiểm tra chỉ số cũ và mới");
                return false;
            }
            try
            {
                int.Parse(txtSoLuong.Text.Trim());
            }
            catch
            {
                ShowError("Số lượng đồng hồ phải có giá trị", txtSoTien.ClientID);
                return false;
            }
            try
            {
                decimal.Parse(txtSoTien.Text.Trim());
            }
            catch
            {
                ShowError("Tiền đồng hồ phải có giá trị", txtSoTien.ClientID);
                return false;
            }
            try
            {
                decimal.Parse(txtNhanCong.Text.Trim());
            }
            catch
            {
                ShowError("Tiền nhân công phải có giá trị", txtNhanCong.ClientID);
                return false;
            }
            
            
            // check ma nhanvien
            if (checktinhtrang.Checked)
            {
                if (string.IsNullOrEmpty(txtNhanVienTH.Text.Trim()))
                {
                    ShowError("Vui lòng chọn nhân viên thực hiện việc thay đồng hồ");
                    btnBrowseNhanVien.Focus();
                    return false;
                }
                else
                {
                    var nv = _nvDao.Get(txtNhanVienTH.Text);
                    if (nv == null)
                    {
                        ShowError("Nhân viên không có trong công ty");
                        btnBrowseNhanVien.Focus();
                        return false;
                    }
                }
            }
            if (string.IsNullOrEmpty(txtNhanVienLapBienBan.Text.Trim()))
            {
                ShowError("Vui lòng chọn nhân viên lập biên bản");
                btnBrowseNhanVienBienBan.Focus();
                return false;
            }
            else
            {
                var nv = _nvDao.Get(txtNhanVienLapBienBan.Text);
                if (nv == null)
                {
                    ShowError("Nhân viên không có trong công ty");
                    btnBrowseNhanVienBienBan.Focus();
                    return false;
                }
            }
            return true;
        }
        #region Khách hàng
        protected void btnFilterKH_Click(object sender, EventArgs e)
        {
            BindKhachHang();
            upnlKhachHang.Update();
            CloseWaitingDialog();
        }

        private void BindKhachHang()
        {
            var danhsach =_khDao.SearchKHForThayDongHo(txtIDKH.Text.Trim(), txtTENKH.Text.Trim(),
                                                           txtMADH.Text.Trim(), txtSOHD.Text.Trim(),
                                                           txtSONHA.Text.Trim(), txtTENDP.Text.Trim(),
                                                           ddlKHUVUC.SelectedValue.Trim(),ddlPHUONG.SelectedValue.Trim(),ddlLoaiKhachHang.SelectedValue);
            gvDanhSach.DataSource = danhsach;
            gvDanhSach.PagerInforText = danhsach.Count.ToString();
            cpeFilter.Collapsed = true;
            gvDanhSach.DataBind();
            tdDanhSach.Visible = true;

            upnlKhachHang.Update();
        }

        protected void btnBrowseKH_Click(object sender, EventArgs e)
        {
            UnblockDialog("divKhachHang");
        }
        protected void BindThongTin(string idkh)
        {
            var data = _thaydonghoDao.GetList(idkh, DateTime.Now.Month);
            gvThongTin.DataSource = data;
            gvThongTin.PagerInforText = data.Count.ToString();
            gvThongTin.DataBind();
            upnlThongTinTDH.Update();
        }
        private void BindStatus(KHACHHANG kh)
        {
            
            SetControlValue(txtIDKH.ClientID, kh.IDKH);
            SetControlValue(txtSODB.ClientID, kh.MADP + kh.DUONGPHU + kh.MADB);
            SetLabel(lblTENKH.ClientID, kh.TENKH);
            SetLabel(lblTENDP.ClientID, kh.DUONGPHO != null ? kh.DUONGPHO.TENDP : "");
            SetLabel(lblTENKV.ClientID, kh.KHUVUC != null ? kh.KHUVUC.TENKV : "");
            
            upnlThongTin.Update();
            var test = _thaydonghoDao.GetList(kh.IDKH, DateTime.Now.Month);
            if (test.Count >= 1)
            {

                Session["idkh"] = kh.IDKH;
                linkdetail.Visible = true;
            }
            else
            {
                linkdetail.Visible = false;
            }
            
        }
        private void BindStatusThayDongHo(THAYDONGHO kh)
        {
            SetControlValue(txtId.ClientID, kh.ID.ToString());
            SetControlValue(txtIDKH.ClientID, kh.IDKH);
            SetControlValue(txtSODB.ClientID, kh.KHACHHANG.MADP+kh.KHACHHANG.DUONGPHU+kh.KHACHHANG.MADB);
            SetLabel(lblTENKH.ClientID, kh.KHACHHANG.TENKH);
            SetLabel(lblTENDP.ClientID, kh.KHACHHANG.DUONGPHO != null ? kh.KHACHHANG.DUONGPHO.TENDP : "");
            SetLabel(lblTENKV.ClientID, kh.KHACHHANG.KHUVUC != null ? kh.KHACHHANG.KHUVUC.TENKV : "");
            SetControlValue(txtChiSoCu.ClientID, kh.CHISOCU.ToString());
            SetControlValue(txtChiSoMoi.ClientID, kh.CHISOMOI.ToString());
            SetControlValue(txtDonViKiemDinh.ClientID, kh.DONVIKIEMDINH);
            SetControlValue(txtGhiChu.ClientID, kh.GHICHU);
            SetControlValue(txtHanKiemDinh.ClientID, kh.HANKIEMDINH);
            SetControlValue(txtMaDongho.ClientID, kh.MADH);
            SetControlValue(txtNgayHoanThanh.ClientID,kh.NGAYHT.HasValue? kh.NGAYHT.Value.ToString("dd/MM/yyyy"):"");
            SetControlValue(txtNgayThay.ClientID,kh.NGAYTD.HasValue?kh.NGAYTD.Value.ToString("dd/MM/yyyy"):"");
            SetControlValue(txtNgayLapBienBan.ClientID, kh.NGAYLBB.HasValue ? kh.NGAYLBB.Value.ToString("dd/MM/yyyy") : "");
            SetControlValue(txtSoPhieu.ClientID, kh.PHIEUXUAT);
            SetControlValue(txtNgayXuat.ClientID,kh.NGAYXUAT.HasValue?kh.NGAYXUAT.Value.ToString("dd/MM/yyyy"):"");
            SetControlValue(txtSoTem.ClientID,kh.SOTEM);
            SetControlValue(txtSoLuong.ClientID,kh.SOLUONG.HasValue?kh.SOLUONG.Value.ToString():"0");
            SetControlValue(txtSoTien.ClientID,kh.TIEN.HasValue?kh.TIEN.Value.ToString():"0");
            SetControlValue(txtNhanCong.ClientID,kh.TIENNHANCONG.HasValue?kh.TIENNHANCONG.Value.ToString():"0");
            SetControlValue(txtNoiSanXuat.ClientID, kh.NOISANXUAT);
            checkMuaMoi.Checked = kh.ISMUAMOI.HasValue ? kh.ISMUAMOI.Value : false;
            checktinhtrang.Enabled = kh.TINHTRANG.HasValue ? kh.TINHTRANG.Value ? false : true : true;
            var ldh=cboLoaiDh.Items.FindByValue(kh.MALDH);
            if(ldh!=null)
            {
                cboLoaiDh.SelectedIndex=cboLoaiDh.Items.IndexOf(ldh);
            }
            var ldthay = ddlLydoThay.Items.FindByValue(kh.MALYDOTHAY);
            if (ldthay != null)
            {
                ddlLydoThay.SelectedIndex = ddlLydoThay.Items.IndexOf(ldthay);
            }
            SetControlValue(txtNhanVienTH.ClientID, kh.MANVTD);
            var nv = _nvDao.Get(kh.MANVTD);
            if (nv != null)
            {
                SetControlValue(txtTenNhanVien.ClientID, nv.HOTEN);
            }
            SetControlValue(txtNhanVienLapBienBan.ClientID, kh.MANVLBB);
            var nv2 = _nvDao.Get(kh.MANVLBB);
            if (nv2 != null)
            {
                SetControlValue(txtTenNhanVienLapBB.ClientID, nv2.HOTEN);
            }
            var cv = ddlNoiDungCongViec.Items.FindByValue(kh.CONGVIEC);
            if (cv != null)
                ddlNoiDungCongViec.SelectedIndex = ddlNoiDungCongViec.Items.IndexOf(cv);
            upnlThongTin.Update();
        }

        protected void gvDanhSach_RowCommand(object sender,  GridViewCommandEventArgs e)
        {
            try
            {
                var id = e.CommandArgument.ToString();
                switch (e.CommandName)
                {
                    case "SelectSODB":
                        // kiem tra trong tháng trước và tháng này nếu có thay đồng hồ thì báo ra
                        
                        var khachhang = _khDao.Get(id);
                        if (khachhang != null)
                        {
                            
                            BindStatus(khachhang);
                            HideDialog("divKhachHang");
                            CloseWaitingDialog();
                            txtSODB.Focus();
                        }
                        break;

                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        protected void gvDanhSach_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (!e.Row.RowType.Equals(DataControlRowType.DataRow)) return;

            var lnkBtnID = e.Row.FindControl("lnkBtnID") as LinkButton;
            if (lnkBtnID == null) return;
            lnkBtnID.Attributes.Add("onclick", "onClientClickGridItem('" + CommonFunc.UniqueIDWithDollars(lnkBtnID) + "')");
        }

        protected void gvDanhSach_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                // Update page index
                gvDanhSach.PageIndex = e.NewPageIndex;

                // Bind data for grid
                BindKhachHang();
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }
        #endregion

        private bool IsValidate()
        {
            try
            {
                DateTimeUtil.GetVietNamDate(txtNgayThay.Text.Trim());
            }
            catch
            {
                ShowError("Ngày thay không có thực", txtNgayThay.ClientID);
                return false;
            }

            try
            {
                DateTimeUtil.GetVietNamDate(txtNgayHoanThanh.Text.Trim());
            }
            catch
            {
                ShowError("Ngày hoàn thành không có thực", txtNgayHoanThanh.ClientID);
                return false;
            }
            try
            {
                DateTimeUtil.GetVietNamDate(txtNgayLapBienBan.Text.Trim());
            }
            catch
            {
                ShowError("Ngày lập biên bản không có thực", txtNgayLapBienBan.ClientID);
                return false;
            }
            return true;
        }

        private void ClearForm()
        {
            
            UpdateMode = Mode.Create;
            txtIDKH.Text = "";
            lblTENKH.Text = "";
            lblTENDP.Text = "";
            lblTENKV.Text = "";
            txtGhiChu.Text = "";
            txtNhanVienTH.Text = "";
            txtTenNhanVien.Text = "";
            txtChiSoCu.Text = "";
            txtChiSoMoi.Text = "";
            txtSODB.Text = "";
            txtMADH.Text = "";
            txtMaDongho.Text = "";
            txtSoTem.Text = "";
            txtNoiSanXuat.Text = "";
            txtSoPhieu.Text = "";
            txtSoLuong.Text = "1";
            txtSoTien.Text = "0";
            txtNhanCong.Text = "50000";
            txtDonViKiemDinh.Text = "";
            txtId.Text = "";
            txtTenNhanVienLapBB.Text = "";
            txtNhanVienLapBienBan.Text = "";
            checktinhtrang.Enabled = true;
            linkdetail.Visible = false;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            
            if (!HasInsertPermission)
            {
                CloseWaitingDialog();
                ShowInfor(Resources.Message.WARN_PERMISSION_DENIED);
                return;
            }

            if (!IsValidate())
            {
                CloseWaitingDialog();
                return;
            }

            try
            {
                    if (Isvaliddata() == false)
                    {
                        CloseWaitingDialog();
                        return;
                    }
                    var kh = _khDao.GetKhachHangFromMadb(txtSODB.Text.Trim());
                    if (kh == null)
                    {
                        CloseWaitingDialog();
                        ShowError("Khách hàng không tồn tại", txtSODB.ClientID);
                        return;
                    }

                    kh.THUYLK = ddlKICHCODH.SelectedValue;
                    kh.MALDH = cboLoaiDh.Text.Trim();
                    kh.MADH = txtMaDongho.Text.Trim();
                    kh.NGAYTHAYDH = DateTimeUtil.GetVietNamDate(txtNgayThay.Text.Trim());
                    var nv = _nvDao.Get(txtNhanVienLapBienBan.Text);
                    if (checktinhtrang.Checked)
                    {
                        nv = _nvDao.Get(txtNhanVienTH.Text);
                    }
                    var tdh = Obj;
                    // Nếu là Insert thì tham số cuối là 1. nếu là update thì tham số cuối là 0
                    if(UpdateMode.Equals(Mode.Update))
                        tdh.ID=int.Parse(txtId.Text.Trim());
                    var msg = _khDao.UpdateThayDongHo(kh, tdh, DateTimeUtil.GetVietNamDate(txtNgayHoanThanh.Text.Trim()), txtSoTem.Text.Trim(), txtGhiChu.Text.Trim(),
                        UserEventLog.ClientHost(), UserEventLog.ClientIP(), nv.MANV,UpdateMode.Equals(Mode.Create)?1:0);
                    
                    CloseWaitingDialog();

                    if (!msg.MsgType.Equals(MessageType.Error))
                    {
                        ShowInfor(ResourceLabel.Get(msg));
                        ClearForm();
                        BindGrid();
                        upnlGrid.Update();
                    }
                    else
                    {
                        ShowError("<strong>Lỗi xảy ra</strong>. <br/><br/>Dò lỗi: <br />" +
                            ResourceLabel.Get(msg), txtSODB.ClientID);
                    }
            }
            catch (Exception ex)
            {
                CloseWaitingDialog();
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
            CloseWaitingDialog();
        }

        protected void txtSODB_TextChanged(object sender, EventArgs e)
        {
            var khachhang = _khDao.GetKhachHangFromMadb(txtSODB.Text.Trim());
            if (khachhang != null)
            {
                lblTENKH.Text = khachhang.TENKH;
                lblTENDP.Text = khachhang.DUONGPHO != null ? khachhang.DUONGPHO.TENDP : "";
                lblTENKV.Text = khachhang.KHUVUC != null ? khachhang.KHUVUC.TENKV : "";

             
                CloseWaitingDialog();
                txtSODB.Focus();
            }
            else
            {
                CloseWaitingDialog();
                ShowError("Khách hàng không tồn tại", txtSODB.ClientID);
            }
        }
        
        private void BindGrid()
        {
            /*
            int thang, nam;
            try
            {
                DateTime.ParseExact(txtNAM.Text.Trim(), "yyyy", CultureInfo.CurrentCulture);
                thang = int.Parse(ddlTHANG.SelectedValue);
                nam = int.Parse(txtNAM.Text.Trim());
            }
            catch
            {
                return;
            }
            */

            var list = _khDao.GetThayDongHoList();
            gvKhachHang.DataSource = list;
            gvKhachHang.PagerInforText = list.Count.ToString();
            gvKhachHang.DataBind();

            upnlGrid.Update();
        }

        protected void gvKhachHang_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                // Update page index
                gvKhachHang.PageIndex = e.NewPageIndex;

                // Bind data for grid
                BindGrid();
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        protected void gvKhachHang_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                var id = e.CommandArgument.ToString();
                switch (e.CommandName)
                {
                    case "EditHoSo":
                        
                        var kh = _thaydonghoDao.Get(int.Parse(id));
                        if (kh != null)
                        {
                            BindStatusThayDongHo(kh);

                            UpdateMode = Mode.Update;
                            CloseWaitingDialog();
                            txtSODB.Focus();
                        }
                        break;

                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        protected void gvKhachHang_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (!e.Row.RowType.Equals(DataControlRowType.DataRow)) return;

            var lnkBtnID = e.Row.FindControl("lnkBtnID") as LinkButton;
            if (lnkBtnID == null) return;
            lnkBtnID.Attributes.Add("onclick", "onClientClickGridItem('" + CommonFunc.UniqueIDWithDollars(lnkBtnID) + "')");
        }
        protected void gvThongTin_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                // Update page index
                gvThongTin.PageIndex = e.NewPageIndex;

                // Bind data for grid
                BindThongTin(Session["idkh"].ToString());
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }
        protected void gvThongTin_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (!e.Row.RowType.Equals(DataControlRowType.DataRow)) return;

            var lnkBtnID = e.Row.FindControl("lnkBtnID") as LinkButton;
            if (lnkBtnID == null) return;
            lnkBtnID.Attributes.Add("onclick", "onClientClickGridItem('" + CommonFunc.UniqueIDWithDollars(lnkBtnID) + "')");
        }
        /*
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            int thang, nam;
            try
            {
                DateTime.ParseExact(txtNAM.Text.Trim(), "yyyy", CultureInfo.CurrentCulture);
                thang = int.Parse(ddlTHANG.SelectedValue);
                nam = int.Parse(txtNAM.Text.Trim());
            }
            catch
            {
                CloseWaitingDialog();
                ShowError("Vui lòng nhập năm hợp lệ.", txtNAM.ClientID);
                return;
            }

            var list = _khDao.GetThayDongHoList(thang, nam);
            gvKhachHang.DataSource = list;
            gvKhachHang.PagerInforText = list.Count.ToString();
            gvKhachHang.DataBind();

            ClearForm();

            upnlGrid.Update();
            CloseWaitingDialog();
        }
        */


        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
               
                // Authenticate
                if (!HasDeletePermission)
                {
                    CloseWaitingDialog();
                    ShowError(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                }

                // Get list of ids that to be update
                var strIds = Request["listIds"];
                if ((strIds != null) && (!string.Empty.Equals(strIds)))
                {
                    var objs = new List<THAYDONGHO>();
                    var listIds = strIds.Split(',');

                   
                    //Add ma vao danh sách cần delete
                    objs.AddRange(listIds.Select(ma => _thaydonghoDao.Get(int.Parse(ma))));

                    //TODO: check relation before update list
                    var msg = _thaydonghoDao.DoAction(objs, PageAction.Delete,UserEventLog.ClientIP(),UserEventLog.ClientHost(), LoginInfo.MANV);

                    if (msg.MsgType != MessageType.Error)
                    {
                        CloseWaitingDialog();

                        ShowInfor(ResourceLabel.Get(msg));

                       
                        // Refresh grid view
                        BindGrid();

                        upnlGrid.Update();
                    }
                    else
                    {
                        CloseWaitingDialog();

                        ShowError(ResourceLabel.Get(msg));
                    }
                }
                else
                {
                    CloseWaitingDialog();
                    ShowError("Chọn record để xóa.");
                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
            CloseWaitingDialog();
        }
        private void BindNhanVien()
        {
            var list = _nvDao.Search(txtKeywordNV.Text.Trim(), LoginInfo.NHANVIEN.MACHINHANH);
            gvNhanVien.DataSource = list;
            gvNhanVien.PagerInforText = list.Count.ToString();
            gvNhanVien.DataBind();
        }
        private void BindNhanVienBB()
        {
            var list = _nvDao.Search(txtKeywordNV.Text.Trim(), LoginInfo.NHANVIEN.MACHINHANH);
            gvNhanVienBB.DataSource = list;
            gvNhanVienBB.PagerInforText = list.Count.ToString();
            gvNhanVienBB.DataBind();
        }

        protected void btnFilterNV_Click(object sender, EventArgs e)
        {
            BindNhanVien();
            CloseWaitingDialog();
        }
        protected void btnFilterNVBB_Click(object sender, EventArgs e)
        {
            BindNhanVienBB();
            CloseWaitingDialog();
        }
        protected void gvNhanVien_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (!e.Row.RowType.Equals(DataControlRowType.DataRow)) return;

            var lnkBtnID = e.Row.FindControl("lnkBtnID") as LinkButton;
            if (lnkBtnID == null) return;
            lnkBtnID.Attributes.Add("onclick", "onClientClickGridItem('" + CommonFunc.UniqueIDWithDollars(lnkBtnID) + "')");
        }

        protected void gvNhanVien_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                var id = e.CommandArgument.ToString();

                switch (e.CommandName)
                {
                    case "SelectMANV":
                        var nv = _nvDao.Get(id);
                        if (nv != null)
                        {
                            SetControlValue(txtNhanVienTH.ClientID, nv.MANV);
                            SetControlValue(txtTenNhanVien.ClientID, nv.HOTEN);
                            txtNhanVienTH.Focus();
                        }
                        HideDialog("divNhanVien");
                        CloseWaitingDialog();

                        break;

                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        protected void gvNhanVien_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                // Update page index
                gvNhanVien.PageIndex = e.NewPageIndex;

                // Bind data for grid
                BindNhanVien();
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        protected void btnBrowseNhanVien_Click(object sender, EventArgs e)
        {
            BindNhanVien();
            upnlNhanVien.Update();
            UnblockDialog("divNhanVien");
        }

        protected void gvNhanVienBB_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (!e.Row.RowType.Equals(DataControlRowType.DataRow)) return;

            var lnkBtnID = e.Row.FindControl("lnkBtnID") as LinkButton;
            if (lnkBtnID == null) return;
            lnkBtnID.Attributes.Add("onclick", "onClientClickGridItem('" + CommonFunc.UniqueIDWithDollars(lnkBtnID) + "')");
        }

        protected void gvNhanVienBB_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                var id = e.CommandArgument.ToString();

                switch (e.CommandName)
                {
                    case "SelectMANV":
                        var nv = _nvDao.Get(id);
                        if (nv != null)
                        {
                            SetControlValue(txtNhanVienLapBienBan.ClientID, nv.MANV);
                            SetControlValue(txtTenNhanVienLapBB.ClientID, nv.HOTEN);
                            txtNhanVienLapBienBan.Focus();
                        }
                        HideDialog("divNhanVienBB");
                        CloseWaitingDialog();

                        break;

                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        protected void gvNhanVienBB_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                // Update page index
                gvNhanVienBB.PageIndex = e.NewPageIndex;
                
                // Bind data for grid
                BindNhanVienBB();
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        protected void btnBrowseNhanVienBB_Click(object sender, EventArgs e)
        {
            BindNhanVienBB();
            upnlNhanVienBB.Update();
            UnblockDialog("divNhanVienBB");
        }
        protected void btnHuy_Click(object sender, EventArgs e)
        {
            ClearForm();
            CloseWaitingDialog();
        }

        protected void linkdetail_Click(object sender, EventArgs e)
        {
            BindThongTin(Session["idkh"].ToString());
            UnblockDialog("divThongTinTDH");
        }
    }
}